package com.liujit.auth.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.liujit.auth.domain.result.CaptchaResult;
import com.liujit.common.constants.RedisKeyConstant;
import com.liujit.redis.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 验证码接口
 * @Author: liujun
 * @Date: 2021/7/1 10:32 下午
 */
@RequiredArgsConstructor
@Api(tags = "验证码接口")
@RestController
@RequestMapping("/oauth")
public class CaptchaController {

    private final RedisService redisService;

    @ApiOperation(value = "获取验证码", notes = "获取图片验证码")
    @GetMapping("/captcha")
    public CaptchaResult captcha() {
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String token = IdUtil.simpleUUID();
        String key = RedisKeyConstant.CAPTCHA + token;
        // 存入redis ，默认五分钟
        redisService.set(key, lineCaptcha.getCode(), 5L, TimeUnit.MINUTES);
        return new CaptchaResult() {{
            setToken(token);
            setContent(lineCaptcha.getImageBase64());
        }};
    }
}
